#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer,  Unicode, TIMESTAMP, func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""System Message Content collection has
    id:             自增id（int）
    messageid:      系统消息id（int）
    content:        系统消息内容（string）
    ctime:          创建时间（datetime）
"""

class SystemMessageContentItem(object):

    def to_dict(self):
        res = {}
        res['messageid'] = self.messageid
        res['content'] = self.content
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def to_short_dict(self):
        res = {
            'content': self.content,
            'ctime': self.ctime.strftime('%Y-%m-%d %H:%M:%S')\
                if self.ctime else "",
        }
        return res

    def __repr__(self):
        return "%d" % (self.messageid)


system_message_content_table = Table(
    'system_message_content', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('messageid', Integer, nullable=False),
    Column('content', Unicode(255), nullable=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(SystemMessageContentItem, system_message_content_table)

def create_system_message_content_table_if_not_exist():
    metadata.create_all(engine)


def add_system_message_content_item(p_item):
    item = SystemMessageContentItem()
    item.messagid = p_item['messageid']
    item.content = p_item['content']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_system_message_content_by_meesageid(p_messageid_list):
    try:
        session = Session()
        items = session.query(SystemMessageContentItem) \
            .filter(SystemMessageContentItem.messageid.in_(p_messageid_list)).all()
        res = [item.to_dict() for item in items]
        return res
    except Exception as e:
        session.rollback()
        return None
    finally:
        session.close()

def get_system_message_by_regtime(p_regtime):
    try:
        session = Session()
        items = session.query(SystemMessageContentItem).filter(SystemMessageContentItem.ctime > p_regtime).all()
        res = [item.to_dict() for item in items]
        return res
    except Exception as e:
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == '__main__':
    create_system_message_content_table_if_not_exist()